/**
 * Created by yx on 2017/8/9.
 */
//
// var nowdate = new Date();
// var oneweekdate = new Date(nowdate-7*24*3600*1000);
// // $("#startdate").val(beginDate(oneweekdate));
// // $("#enddate").val(endDate(nowdate));
//
// function beginDate(date) {
//     return endDate(date);
// };
//
// function endDate(date) {
//     return date.getFullYear() + "-" + ("0" + (date.getMonth() + 1)).slice(-2) + "-" + ("0" + date.getDate()).slice(-2);
// };
console.log('keyWord');
$('.date-picker').datepicker({autoclose: true}).next().on(ace.click_event, function () {
    $(this).prev().focus();
});
$('#startDate, #endDate, #startTime, #endTime').datepicker('update');
// $('#endDate').datepicker('update');
// getAllInfo().done(function() {
// 初始化table
$("#keyWord_table").bootstrapTable({
    // 'url': '../serviceType/findAll',
    'url': '/user/searchWord/findSearchWords',
    'toolbar': $('div[data-name="btnCtl"]'),
    'queryParams': queryParams,
    'cache':false,
    'sidePagination': 'server',
    'toolbarAlign': 'right',
    'undefinedText': '-',
    'striped': true,
    'pagination': true,
    'sortable': true, //是否启用排序
    'sortOrder': "asc", //排序方式
    'pageSize': globalPageSize,
    'pageList': [],
    'clickToSelect': true,
    'singleSelect': true,
    'smartDisplay': true,
    'ajaxOptions':{
        headers: {"Authorization": localStorage.token}
    },
    'responseHandler': function (resb) {
        return {
            'total': resb.data.total,
            'rows': resb.data.content
        }
    },
    'onCheck': function() {
        $("button[data-target='#updateModal'], button[data-target='#deleteModal']").removeAttr("disabled");
    },
    'onUncheck': function() {
        $("button[data-target='#updateModal'], button[data-target='#deleteModal']").attr("disabled", 'true');
    },
    'onPageChange': function() {
        if($("#keyWord_table").bootstrapTable('getSelections')[0]){
            $("#keyWord_table").bootstrapTable('uncheckBy', {
                field: 'typeId',
                values: [$("#keyWord_table").bootstrapTable('getSelections')[0].typeId]
            });
        };
    },
    'columns': [{
        'checkbox': true,
        // 'class': 'hide'
    },
        {
            'title': '序号',
            'align': 'center',
            'formatter': function (value, row, index) {
                return index+1;
            }
        },{
            'field': 'word',
            'title': '关键字',
            'align': 'center'
        },{
            'field': 'createTime',
            'title': '创建日期',
            'align': 'center',
            'sortable': true
        }
    ]
});
// });

//请求服务数据时所传参数
function queryParams(params){
    if($('#startDate').val() != '' || $('#endDate').val() != '') {
        return {
            startTime: $('#startDate').val() + " 00:00:00",
            endTime: $('#endDate').val() + " 23:59:59",
            limit : params.limit, //每一页的数据行数，默认是上面设置的10(pageSize)
            offset : params.offset,
            startTime: $('#startDate').val() == ""?null:$('#startDate').val(),
            endTime:$('#endDate').val() == ""?null:$('#endDate').val()
        };
    }else {
        return {
            limit : params.limit, //每一页的数据行数，默认是上面设置的10(pageSize)
            offset : params.offset
        };
    }
}

/**
 * 关键字查询ajax
 */
function keyWordQuery() {
    if($("#startDate").val()== ''&&$("#endDate").val()== ''){
        $('#keyWord_table').bootstrapTable('refreshOptions',{pageNumber:1,pageSize:globalPageSize});
    }else{
        $.ajaxSetup({cache:false});
        $.ajax({
            type: "GET",
            // url: "/community/forummessage/getFindMsg",
            url: "/user/searchWord/findSearchWords?startTime="+$('#startDate').val()+" 00:00:00&endTime="+$('#endDate').val()+" 23:59:59&limit="+globalPageSize+"&offset=0",
            // data: {
            //     "msgContent": $('#contentName').val(),
            //     'msgType': $('.selectClassify').val(),
            //     'createDateS': $('#startdate').val(),
            //     'createDateE': $('#enddate').val()
            // },
            dataType: 'json',
            // contentType: "application/json",
            beforeSend: function (request) {
                request.setRequestHeader("Authorization", sessionStorage.token);
            },
            success: function(resb) {
                console.log(resb);
                if (resb.data.length != 0) {
                    $("#keyWord_table").bootstrapTable('load', {
                        'total': resb.data.total,
                        'rows': resb.data.content
                    });
                } else {
                    $("#keyWord_table").bootstrapTable('removeAll');
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
    }
    return false;
}

$("#dataSearch").click(function () {
    keyWordQuery();
    return;
});

// 导出
$("#exportExcel").click(function () {
    var obj = $("#exportForm").validationEngine('validate', {
        promptPosition: "centerRight",
        scroll: false,
        autoPositionUpdate: true,
        validationEventTrigger:'blur',
        binded:true,
        autoHidePrompt: true,
        autoHideDelay: 3000,
        showOneMessage:true
    });
    if (!obj) {
        return false;
    };
    exportExcel();
});

function exportExcel() {
    var offset = $("#offset").val(),
           limit = $("#limit").val(),
           startTime = $("#startTime").val(),
           endTime = $("#endTime").val();
    var url = '/user/searchWord/exportSearchWords?' + 'offset=' + offset + '&limit=' + limit +
        (startTime != '' ? '&startTime=' + startTime + ' 00:00:00' : '') + (endTime != '' ? '&endTime=' + endTime + ' 23:59:59' : '');
    if ($("#downloadcsv")[0]) {
        $('#downloadcsv').attr('src', url);
    } else {
        $('body').append("<iframe id=\"downloadcsv\" style=\"display:none\"></iframe>");
        $('#downloadcsv').attr('src', url);
    }
};


/**
 * 列表操作(新增，更新，删除)
 * @param action [add/update/remove]
 * @param data
 *               [add/update 数据结构 {name: string, description: string, listAuthorityId: array} ]
 *               [delete 数据结构 {roleId: int}]
 * @param async/scync [default async]
 */
// function industryManagement(action, data, async) {
//     var url = null;
//     (async === false) ? async = false: async = true;
//     if (action === 'add') {
//         url = '/user/job/addJob?'+objTostring(data);
//     } else if(action === 'update'){
//         url = '/user/job/updateJob?'+objTostring(data);
//     }else {
//         url = '/user/job/deleteJob?'+objTostring(data);
//     }
//     return $.ajax({
//         type: "GET",
//         url: url,
//         // data: JSON.stringify(data),
//         contentType: "application/json",
//         dataType: 'json',
//         beforeSend: function (request) {
//             request.setRequestHeader("Authorization", localStorage.token);
//         },
//         async: async,
//         success: function(resb) {
//             alert(resb.message);
//         },
//         error: function(XMLHttpRequest, textStatus, errorThrown) {
//             // console.log(XMLHttpRequest, textStatus, errorThrown);
//             alert(textStatus);
//         }
//     });
// }

function objTostring(obj) {
    var arr = [];
    for(var i in obj) {
        arr.push(i+"="+obj[i]);
    }
    console.log(arr.join('&'));
    return arr.join('&');
}
